package com.echo.servlet.UserServlet;

import com.echo.entity.User;
import com.echo.service.UserService;
import com.echo.util.BusinessException;
import com.echo.servlet.BaseServlet;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet({"/login", "/echo-network/login"})
public class LoginServlet extends BaseServlet {
    private UserService userService = new UserService();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置编码
        setRequestEncoding(request);
        response.setContentType("text/html;charset=UTF-8");

        // 获取请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 只有当用户名和密码都不为空时才进行登录验证
        if (username != null && password != null && !username.isEmpty() && !password.isEmpty()) {
            try {
                // 调用UserService进行实际的用户验证
                User user = userService.login(username, password);
                
                // 登录成功：使用UserService.findUserById获取包含完整信息（包括createTime）的用户对象
                User fullUser = userService.findUserById(user.getId());
                
                // 存入Session
                request.getSession().setAttribute("loginUser", fullUser);
                
                // 获取returnUrl参数，如果存在则重定向到该URL，否则重定向到个人资料页面
                String returnUrl = request.getParameter("returnUrl");
                if (returnUrl != null && !returnUrl.isEmpty()) {
                    // 验证returnUrl是本站地址，防止XSS攻击
                    if (returnUrl.startsWith(request.getContextPath())) {
                        response.sendRedirect(returnUrl);
                    } else {
                        // 不是本站地址，使用默认地址
                        response.sendRedirect(request.getContextPath() + "/profile-show");
                    }
                } else {
                    // 没有returnUrl参数，重定向到个人资料页面
                    response.sendRedirect(request.getContextPath() + "/profile-show");
                }
            } catch (BusinessException e) {
                // 业务异常，显示具体的错误信息
                response.sendRedirect(request.getContextPath() + "/login.html?errorMsg=" + java.net.URLEncoder.encode(e.getMessage(), "UTF-8"));
            } catch (Exception e) {
                // 捕获其他异常，提供更准确的错误信息
                e.printStackTrace();
                String errorMessage = "登录失败：" + e.getMessage();
                // 限制错误消息长度，避免URL过长
                if (errorMessage.length() > 100) {
                    errorMessage = errorMessage.substring(0, 100) + "...";
                }
                response.sendRedirect(request.getContextPath() + "/login.html?errorMsg=" + java.net.URLEncoder.encode(errorMessage, "UTF-8"));
            }
        } else {
            // 如果参数为空，直接跳转到登录页面，不显示错误信息
            response.sendRedirect(request.getContextPath() + "/login.html");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}